//index.js
//获取应用实例
var app = getApp();
var page = 0;
var loadMore = function(that) {

  that.setData({
    hidden: false
  });
  wx.request({
    url: 'http://' + app.globalData.IP + ':9588/wx/selectAll',
    success: function(res) {

      var list1 = that.data.list;
      console.log(page)
      console.log(that.data.list.length)
      console.log(res.data.pushuser.length)
      setTimeout(function(){
        if (that.data.list.length <= res.data.pushuser.length) {
          var count = Math.ceil(res.data.pushuser.length / 5);
          var i = res.data.pushuser.length - 5 * (count - page)
          for (var a = 0; a < 5; a++) {
            if (res.data.pushuser[i] != null) {
              list1.push(res.data.pushuser[i]);
            }

            i++;
          }
        }
        that.setData({
          list: list1,
        });
        page++;
        that.setData({
          hidden: true
        });

      },500)
      

    }
  });
}


Page({
  //   onPullDownRefresh: function () {
  //     wx.showNavigationBarLoading()
  //     this.begin()
  //     wx.hideNavigationBarLoading() //完成停止加载
  //     wx.stopPullDownRefresh() //停止下拉刷新
  //  },


  onReady: function(e) {
    // 使用 wx.createAudioContext 获取 audio 上下文 context
    this.audioCtx = wx.createAudioContext('myAudio')
  },
  data: {
    runData: "",
    today: '今日步数',
    poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
    name: '此时此刻',
    author: '许巍',
    src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
    sessionkey: "",
    iv: "",
    encryptedData: "",
    productmap: [],
    total: "",
    hidden: true,
    scrollTop: 0,
    scrollHeight: 0,
    list: [],
    currectlist:[]
  },

  audioPlay: function() {
    this.audioCtx.play()
  },
  audioPause: function() {
    this.audioCtx.pause()
  },
  audio14: function() {
    this.audioCtx.seek(14)
  },
  //事件处理函数
  index_exchange: function(e) {
    wx.navigateTo({
      url: '../index/exchange',
    })
    wx.setStorageSync("productName", e.currentTarget.dataset.ids)
  },
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onShow: function() {
    this.begin()
  },
  onLoad: function() {
    this.begin();
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          scrollHeight: res.windowHeight
        });

      }
    });
    loadMore(that);
  },

  begin: function() {
    var t = this;
    wx.getWeRunData({
      success: function(res) {
        wx.request({
          url: 'http://' + app.globalData.IP + ':9588/wx/wxgetrundata',
          data: {
            data: res.encryptedData,
            iv: res.iv,
            key: wx.getStorageSync("sessionkey"),
          },
          success: function (dat) {
            wx.setStorageSync("steplist", dat.data.stepInfoList[dat.data.stepInfoList.length - 1].step)
            var stepDetails = {
              type: 3,
              stepNum: wx.getStorageSync("steplist"),
              stepTime: new Date,
              openId:wx.getStorageSync('openId')
            };
            wx.request({
              url: 'http://' + app.globalData.IP+':9588/wx/stepCheck',
              method:"POST",
              data: stepDetails,
              dataType:"json",
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              success:function(data){
                t.setData({
                  runData: data.data
                })
              }
            })


          }
        })
      }
    })
    wx.request({
      url: 'http://' + app.globalData.IP + ':9588/wx/selectAll',
      success: function(data) {
        t.setData({
          productmap: data.data
        })
      }
    })
    this.getWXUserInfo();
  },

  add_step:function(e){
    var t=this;
    var bala = e.currentTarget.dataset.step;
    var stepType = e.currentTarget.dataset.steptype;
    wx.getSetting({
      success:res=>{
        if (res.authSetting['scope.werun']){
          if (bala < 2000) {
            wx.showToast({
              title: '步数不足2000，不足以兑换',
              icon: "none",
            })
          } else {
            var bal = e.currentTarget.dataset.step / 2000;
            wx.request({
              url: 'http://' + app.globalData.IP+':9588/wx/modifyBalance',
              data: {
                openId: wx.getStorageSync("openId"),
                balance: parseInt(bal),
                algorithm: "+"
              },
              method: "GET",
              success: function (res) {
                if (res) {
                  wx.showToast({
                    title: '成功兑换' + parseInt(bal) + '燃力币',
                    icon: "none"
                  })
                  t.setData({
                    runData: bala - (parseInt(bal) * 2000)
                  });

                  var stepDetails = {
                    type: stepType,
                    stepNum: (parseInt(bal) * 2000),
                    stepTime: new Date,
                  };

                  t.addStepRecord(stepDetails);
                  t.getWXUserInfo();
                } else {
                  wx.showToast({
                    title: '请稍后兑换',
                    icon: "loading"
                  })
                }
              }
            })
          }

        }else{
          wx.showToast({
            title: '微信步数未授权，无法兑换',
            icon:'none',
          })
        }
      }
    })
  },

  getWXUserInfo: function() {
    var t = this;
    wx.request({
      url: 'http://' + app.globalData.IP + ':9588/wx/getUserInfo',
      data: {
        openId: wx.getStorageSync('openId')
      },
      success: function(data) {
        wx.getSetting({
          success: function(res) {
            if (res.authSetting['scope.userInfo']) {
              t.setData({
                total: data.data.balance
              })
            }
          }
        })
      }
    })
  },

  addStepRecord: function(stepDetails) {
    stepDetails.openId = wx.getStorageSync("openId")
    var t=this;
    wx.request({
      url: 'http://' + app.globalData.IP + ':9588/wx/addStepRecord',
      method: "POST",
      data: stepDetails,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      dataType: "json",
      success: function() {
        console.log("成功")
      }
    })
  },
  //页面滑动到底部
  bindDownLoad: function() {
    var that = this;
    loadMore(that);

  },
  scroll: function(event) {
    //该方法绑定了页面滚动时的事件，我这里记录了当前的position.y的值,为了请求数据之后把页面定位到这里来。
    this.setData({
      scrollTop: event.detail.scrollTop
    });
  },
  topLoad: function(event) {
    //   该方法绑定了页面滑动到顶部的事件，然后做上拉刷新
    page = 0;
    this.setData({
      list: [],
      scrollTop: 0
    });
    loadMore(this);

  }





})